/**
 * @a https://leetcode.cn/problems/matrix-block-sum/
 */

#include "common.h"
class Solution
{
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>> &mat, int k)
    {
        int row = mat.size(), col = mat[0].size();
        vector<vector<int>> mat_presum(row + 1, vector<int>(col + 1, 0));

        for (int i = 1; i <= row; ++i)
        {
            for (int j = 1; j <= col; ++j)
            {
                mat_presum[i][j] = mat_presum[i][j - 1] 
                                + mat_presum[i - 1][j] 
                                - mat_presum[i - 1][j - 1] 
                                + mat[i - 1][j - 1];
            }
        }

        vector<vector<int>> ret(row, vector<int>(col, 0));
        for (int i = 0; i < row; ++i)
        {
            for (int j = 0; j < col; ++j)
            {
                int y1 = max(i - k, 0), x1 = max(j - k, 0);
                int y2 = min(i + k, row - 1), x2 = min(j + k, col - 1);
                ++y1,++y2,++x1,++x2;
                ret[i][j] = mat_presum[y2][x2] + mat_presum[y1 - 1][x1 - 1] - mat_presum[y2][x1 - 1] - mat_presum[y1 - 1][x2];
            }
        }
        return ret;
    }
};